package edu.isquen.core.document.action;

import org.apache.commons.lang.StringUtils;

import com.opensymphony.xwork2.Preparable;

import edu.isquen.core.base.action.BaseAction;
import edu.isquen.core.document.model.Document;
import edu.isquen.core.document.service.DocumentService;
import edu.isquen.core.form.model.Form;
import edu.isquen.core.form.service.FormService;
import edu.isquen.core.user.model.User;
import edu.isquen.util.cache.MemoryCacheUtil;
import edu.isquen.util.factory.ServiceFactory;

public class DocumentAction extends BaseAction<Document> implements Preparable{
	
	private static final long serialVersionUID = -6678421343165897001L;
	
	private String _formid;
	
	public DocumentAction() throws Exception {
		super(ServiceFactory.createProcess(DocumentService.class.getName()), new Document());
	}
	
	public void prepare() throws Exception{
	}
	
	public String doNew() {
		try {
			FormService formService = (FormService) ServiceFactory.createProcess(FormService.class);
			User user = getUser();
			Form form = (Form) formService.doView(get_formid());
			if (form != null) {
				Document newDoc = ((DocumentService) this.service).doNew(form, user, getParams());
				setValObj(newDoc);
				MemoryCacheUtil.putToPrivateSpace(newDoc.getId(), newDoc);
			}
			return SUCCESS;
		} catch (Exception e) {
			addFieldError("1", e.getMessage());
			e.printStackTrace();
			return INPUT;
		}
	}
	
	public String doSave() {
		try {
			User user = this.getUser();
			Document doc = (Document) getValObj();
			if (!StringUtils.isBlank(doc.getId())) {
				doc = (Document) MemoryCacheUtil.getFromPrivateSpace(doc.getId());
				if (doc != null) {
					doc.setId(doc.getId());
				}
			}
			String formid=get_formid();
			if(formid==null || formid.equals("")){
				formid=doc.getFormId();
			}
			FormService formService = (FormService) ServiceFactory.createProcess(FormService.class);
			Form form = (Form) formService.doView(formid);
			Document valObj = form.createDocument(doc, getParams(), user);
			((DocumentService) this.service).doCreateOrUpdate(valObj, user);

			setValObj(valObj);
			//this.addActionMessage("{*[Save_Success]*}");
		} catch (Exception e) {
			this.addFieldError("1", e.getMessage());
			e.printStackTrace();
			return INPUT;
		}
		return SUCCESS;
	}
	
	public String get_formid() {
		return _formid;
	}

	public void set_formid(String formid) {
		_formid = formid;
	}
}
